<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Setting /></el-icon>
            系统设置
          </span>
        </div>
      </template>

      <el-form 
        :model="settingsForm" 
        :rules="settingsRules" 
        ref="settingsFormRef" 
        label-width="120px"
        class="settings-form"
      >
        <el-form-item label="API 接口地址" prop="apiBaseURL">
          <el-input 
            v-model="settingsForm.apiBaseURL" 
            placeholder="请输入 API 接口地址，例如: http://127.0.0.1:8003"
            clearable
          >
            <template #prefix>
              <el-icon><Link /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">
            <el-text type="info" size="small">
              设置后端 API 接口的基础地址，修改后需要重新登录生效
            </el-text>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveSettings" :loading="saving">
            <el-icon><Check /></el-icon>
            保存设置
          </el-button>
          <el-button @click="resetToDefault">
            <el-icon><Refresh /></el-icon>
            重置默认
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Link, Check, Refresh } from '@element-plus/icons-vue'
import apiConfig from '../utils/apiConfig'

// 响应式数据
const settingsFormRef = ref()
const saving = ref(false)

const settingsForm = reactive({
  apiBaseURL: apiConfig.getBaseURLSync() // 使用同步方法初始化
})

// 组件挂载时异步加载配置
onMounted(async () => {
  try {
    const baseURL = await apiConfig.getBaseURL()
    settingsForm.apiBaseURL = baseURL
  } catch (error) {
    console.warn('加载配置失败，使用默认值:', error)
    settingsForm.apiBaseURL = 'http://127.0.0.1:8003'
  }
})

const settingsRules = {
  apiBaseURL: [
    { required: true, message: '请输入 API 接口地址', trigger: 'blur' },
    { 
      pattern: /^https?:\/\/.+/,
      message: '请输入有效的 URL 地址，例如: http://127.0.0.1:8003',
      trigger: 'blur'
    }
  ]
}

// 保存设置
const saveSettings = async () => {
  try {
    await settingsFormRef.value.validate()
    
    saving.value = true
    
    // 更新 API 配置
    apiConfig.setBaseURL(settingsForm.apiBaseURL)
    
    ElMessage.success('设置保存成功')
    
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  } finally {
    saving.value = false
  }
}

// 重置为默认值
const resetToDefault = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置为默认设置吗？这将清除所有自定义配置。',
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    settingsForm.apiBaseURL = 'http://127.0.0.1:8003'
    apiConfig.resetToDefault()
    
    ElMessage.success('已重置为默认设置')
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置设置失败:', error)
      ElMessage.error('重置设置失败')
    }
  }
}
</script>

<style scoped>
.settings-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.settings-form {
  margin-top: 20px;
}

.form-tip {
  margin-top: 8px;
}

.test-result-card {
  margin-top: 20px;
}

.test-result {
  margin-top: 10px;
}
</style> 